package com.yj.springbootstudy.schedule;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class JavaScheduleTest {


    public static void main(String[] args) {

//    timer();
        executorSchedule();
    }

    public static void runnable(){
        // 1.使用多线程得方式实现定时任务
        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(1000);
                        System.out.println("todo...");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        new Thread(runnable).start();
    }

    public static void timer(){
        //2.使用timer执行定时任务
        Timer timer = new Timer();
        timer.schedule(new MyTimer(),1000,3); //1s 后开始调度，每2s 执行一次
    }

    public static void executorSchedule(){

        ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(2);
        threadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println("todo...");
            }
        },2, 3,TimeUnit.SECONDS);
     }

}

class MyTimer extends TimerTask{

    @Override
    public void run() {
        System.out.println("todo...");
    }
}